using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Configuration;
using System.Configuration.Provider;
using System.Web.Configuration;


namespace Ajax.Logging
{
    public class ExceptionLogManager
    {
        private static ExceptionLogProvider _provider;
        private static ExceptionLogProviderCollection _providers;
        private static object _lock = new object();

        public ExceptionLogProvider Provider
        {
            [DebuggerStepThrough()]
            get
            {
                LoadProviders();

                return _provider;
            }
        }

        public ExceptionLogProviderCollection Providers
        {
            [DebuggerStepThrough()]
            get
            {
                LoadProviders();

                return _providers;
            }
        }

        [DebuggerStepThrough()]
        public static void Log(ExceptionInfo exception)
        {
            LoadProviders();

            _provider.Log(exception);
        }

        [DebuggerStepThrough()]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", Justification = "Assembly is not localized")]
        private static void LoadProviders()
        {
            if (_provider == null)
            {
                lock (_lock)
                {
                    if (_provider == null)
                    {
                        ExceptionLogProviderSettings setting = (ExceptionLogProviderSettings)ConfigurationManager.GetSection(ExceptionLogProviderSettings.SectionName);

                        _providers = new ExceptionLogProviderCollection();

                        ProvidersHelper.InstantiateProviders(setting.Providers, _providers, typeof(ExceptionLogProvider));

                        _provider = _providers[setting.DefaultProvider];

                        if (_provider == null)
                        {
                            throw new ProviderException("Unable to load default ExceptionLogProvider");
                        }
                    }
                }
            }
        }
    }
}
